package com.liangxy.news.ui.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;

import com.liangxy.news.model.News;
import com.liangxy.news.repository.NewsRepository;

import java.util.List;

/**
 * ViewModel for news list
 */
public class NewsViewModel extends AndroidViewModel {
    
    private final NewsRepository repository;
    private final MutableLiveData<String> currentCategory = new MutableLiveData<>(NewsRepository.TYPE_TOP);
    private final MutableLiveData<String> currentUserId = new MutableLiveData<>();
    private final MutableLiveData<Boolean> shouldRefresh = new MutableLiveData<>(false);
    
    // 当前显示模式
    public static final int MODE_CATEGORY = 0;
    public static final int MODE_FOLLOWED = 1;
    public static final int MODE_HISTORY = 2;
    private final MutableLiveData<Integer> currentMode = new MutableLiveData<>(MODE_CATEGORY);
    
    // 中介LiveData，根据不同模式切换数据源
    private final MediatorLiveData<List<News>> news = new MediatorLiveData<>();
    
    public NewsViewModel(@NonNull Application application) {
        super(application);
        repository = NewsRepository.getInstance(application);
        
        // 监听模式变化，切换数据源
        currentMode.observeForever(mode -> updateNewsSource(mode));
    }
    
    private void updateNewsSource(int mode) {
        // 清除之前的数据源
        news.setValue(null);
        
        switch (mode) {
            case MODE_CATEGORY:
                // 监听分类新闻数据变化
                news.addSource(
                        Transformations.switchMap(currentCategory, category -> 
                                repository.getNewsByCategory(category, 1, 20, shouldRefresh.getValue())), 
                        newsList -> news.setValue(newsList)
                );
                break;
            case MODE_FOLLOWED:
                // 监听关注新闻数据变化
                news.addSource(
                        Transformations.switchMap(currentUserId, userId -> 
                                repository.getFollowedNews(userId)), 
                        newsList -> news.setValue(newsList)
                );
                break;
            case MODE_HISTORY:
                // 监听历史记录数据变化
                news.addSource(repository.getNewsHistory(), newsList -> news.setValue(newsList));
                break;
        }
    }
    
    /**
     * Set current news category
     * @param category News category
     */
    public void setCategory(String category) {
        if (!category.equals(currentCategory.getValue())) {
            currentCategory.setValue(category);
            // 切换分类时自动刷新
            refreshNews();
        }
    }
    
    /**
     * Set current user ID
     * @param userId User ID
     */
    public void setUserId(String userId) {
        if ((userId == null && currentUserId.getValue() != null) || 
            (userId != null && !userId.equals(currentUserId.getValue()))) {
            currentUserId.setValue(userId);
        }
    }
    
    /**
     * Set current display mode
     * @param mode Display mode
     */
    public void setMode(int mode) {
        if (mode != currentMode.getValue()) {
            currentMode.setValue(mode);
        }
    }
    
    /**
     * Refresh news data from API
     */
    public void refreshNews() {
        if (currentMode.getValue() == MODE_CATEGORY && currentCategory.getValue() != null) {
            shouldRefresh.setValue(true);
            repository.refreshNewsByCategory(currentCategory.getValue(), 1, 20);
            shouldRefresh.setValue(false);
        }
    }
    
    /**
     * Get news list
     * @return LiveData list of news
     */
    public LiveData<List<News>> getNews() {
        return news;
    }
    
    /**
     * Get loading state
     * @return LiveData loading state
     */
    public LiveData<Boolean> getIsLoading() {
        return repository.getIsLoading();
    }
    
    /**
     * Get error message
     * @return LiveData error message
     */
    public LiveData<String> getErrorMessage() {
        return repository.getErrorMessage();
    }
    
    /**
     * Follow news
     * @param newsId News ID
     */
    public void followNews(String newsId) {
        String userId = currentUserId.getValue();
        if (userId != null && !userId.isEmpty()) {
            repository.followNews(userId, newsId);
        }
    }
    
    /**
     * Unfollow news
     * @param newsId News ID
     */
    public void unfollowNews(String newsId) {
        String userId = currentUserId.getValue();
        if (userId != null && !userId.isEmpty()) {
            repository.unfollowNews(userId, newsId);
        }
    }
    
    /**
     * Check if user follows a news
     * @param newsId News ID
     * @return Whether the user follows the news
     */
    public boolean isFollowing(String newsId) {
        String userId = currentUserId.getValue();
        return repository.isFollowing(userId, newsId);
    }
    
    /**
     * Record news read
     * @param newsId News ID
     */
    public void recordNewsRead(String newsId) {
        repository.recordNewsRead(newsId);
    }
} 